package dcclient

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/sirupsen/logrus"
	"strconv"
)

const (
	connectInit = iota
	deviceOnline
	deviceOffline
	waitTimeout
)

// MQTTClient is entity struct
type MQTTClient struct {
	Domain   string
	Port     string
	UID      string
	PID      string
	Suffix   string
	Password string

	chDone       chan bool
	ChOnOutDelay chan bool

	adapter      mqtt.Client
	deviceStatus interface{}
	onlineFlag   int
	DeviceType   int

	onMessageHandler func(mqtt.
				Client, mqtt.Message)
	onConnectHandler        mqtt.OnConnectHandler
	onConnectionLostHandler mqtt.ConnectionLostHandler
}

var clientIDIndex int = 1

// Connect use for adapter paho mqtt connect
func (client *MQTTClient) Connect() mqtt.Client {
	defer func() {
		if r := recover(); r != nil {
			logrus.Infof("connect failed ret = %v", r)
		}
	}()

	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("ssl://%s:%s", client.Domain, client.Port))
	opts.SetClientID("aligenie_" + strconv.Itoa(clientIDIndex))
	clientIDIndex++
	opts.SetUsername("and_" + client.UID + client.Suffix)
	opts.SetPassword(client.Password)
	opts.SetDefaultPublishHandler(client.onMessageHandler) //发布的时候 的handler
	opts.SetAutoReconnect(false)                           //不重新连接
	opts.OnConnect = client.onConnectHandler
	opts.OnConnectionLost = client.onConnectionLostHandler
	client.adapter = mqtt.NewClient(opts)
	if token := client.adapter.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	return client.adapter
}
